//从中序与后序遍历序列构造二叉树
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class SolutionCteateTree2 {
     public int postIndex;
    public TreeNode buildTree(int[] inorder, int[] postorder) {

        postIndex = postorder.length-1;
        return buildTreeChilde(postorder,inorder,0,inorder.length-1);
    }


    private TreeNode buildTreeChilde(int[] postorder,int[] inorder,int inbegin,int inend) {
        if(inbegin > inend) {
            return null;//没有 左树 或者 没有 右树 
        }
        TreeNode root = new TreeNode(postorder[postIndex]);

        int rootIndex = findIndexRoot(inorder,inbegin,inend,postorder[postIndex]);
        if(rootIndex == -1) {
            return null;
        }
        postIndex--;

        root.right = buildTreeChilde(postorder,inorder,rootIndex+1,inend);

        root.left = buildTreeChilde(postorder,inorder,inbegin,rootIndex-1);
        
        return root;
    }

    private int findIndexRoot(int[] inorder,int inbegin, int inend,int key) {

        for(int i = inbegin; i <= inend;i++) {
            if(inorder[i] == key) {
                return i;
            }
        }
        return -1;
    }
}